﻿using netDxf;
using netDxf.Entities;
using MCPlatform.Dxf.Interfaces;
using MCPlatform.Dxf.Entities;
using MCPlatform.Dxf.Factories;
using System.IO;
using System.Windows;


namespace MCPlatform.Dxf.Readers
{
    public class DxfReader : IDxfReader
    {
        // 使用具体的实体类型作为键，存储与之关联的PathEntityBase对象
        public Dictionary<Type, List<PathEntityBase>> entitiesWithPaths =
            new Dictionary<Type, List<PathEntityBase>>();
        
        public DxfReader() { }

        public  List<PathEntityBase> ReadFromFile(string filePath)
        {
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException("The file was not found.", filePath);
            }
            try
            {
                using (var stream = File.OpenRead(filePath))
                {
                    return ReadFromStream(stream);
                }
            }
            catch (Exception)
            {
                throw;
            }
           
        }


        public List<PathEntityBase> ReadFromStream(Stream stream)
        {
            var entities = new List<PathEntityBase>();

            try
            {
                DxfDocument dxfDocument = DxfDocument.Load(stream);
                
                foreach (EntityObject entity in dxfDocument.Entities.All)
                {
                    PathEntityBase? PathEntityBase = CreatePathEntityBaseFromEntity(entity);
                    

                    if (PathEntityBase != null)
                    {
                        // 将PathEntityBase添加到entities列表，并同时更新字典
                        entities.Add(PathEntityBase);
                        AddPathEntityBaseToDictionary(entity.GetType(), PathEntityBase);
                    }
                    else
                    {
                        continue;
                        // 记录或处理不支持的实体类型
                       //Console.WriteLine($"Unsupported entity type: {entity.GetType().Name}");
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载文件失败！格式不兼容{ex}");
                
               // throw new InvalidOperationException("Failed to load DXF document.", ex);
            }

            return entities;
        }

        private void AddPathEntityBaseToDictionary(Type entityType, PathEntityBase PathEntityBase)
        {
            // 如果字典中不存在该类型的键，则添加新列表
            if (!entitiesWithPaths.ContainsKey(entityType))
            {
                entitiesWithPaths[entityType] = new List<PathEntityBase>();
            }
            // 将PathEntityBase添加到对应类型的列表中
            entitiesWithPaths[entityType].Add(PathEntityBase);
        }

        private PathEntityBase? CreatePathEntityBaseFromEntity(EntityObject entity)
        {
            var factoryManager = new PathEntityFactoryManager();
            return factoryManager.CreatePathEntity(entity);
        }

        
    }
}
